<template>
  <div style="background: #ffffff;">
    <!-- 搜索栏 -->
    <div>
      <el-row :gutter="24">
        <el-col :span="24" style="display: flex; align-items: center; margin-bottom: 8px">
          <el-input v-model="searchValue" placeholder="请输入任务名称/ID" clearable prefix-icon="el-icon-search"
            style="flex: 1; max-width: 250px; margin-right: 10px" @clear="handleClearSearch"></el-input>
          <el-button type="info" plain @click="handleSearch">查询</el-button>
          <el-button type="primary" plain style="margin-left: 10px" @click="openDrawer">创建任务</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 表格 -->
    <div class="table">
      <el-table :data="tableData" stripe border size="small" :loading="loading"
        style="width: 100%; margin-bottom: 20px">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="序号" width="80" align="center" sortable>
          <template v-slot="scope">
            {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="taskId" label="任务ID" show-overflow-tooltip></el-table-column>
        <el-table-column prop="splitMethod" label="数据集" show-overflow-tooltip></el-table-column>
        <el-table-column prop="batchSize" label="批量大小" align="center"></el-table-column>
        <el-table-column prop="aggregationRounds" label="聚合轮次" align="center"></el-table-column>
        <el-table-column prop="learningRate" label="学习率" align="center"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" align="center">
          <template v-slot="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <el-button plain :type="getButtonType(scope.row.status)" size="mini"
              @click="scope.row.status === '待执行' ? handleEdit(scope.row) : null" :disabled="scope.row.status !== '待执行'">
              {{ getButtonText(scope.row.status) }}
            </el-button>
            <el-button plain type="success" size="mini" @click="handleDetail(scope.row)">
              详细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" @size-change="handlePageSizeChange" @current-change="handleCurrentPageChange"
        :current-page="pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-- 侧边栏 -->
    <el-drawer title="创建任务" :visible.sync="drawerVisible" direction="rtl" size="70%">
      <div class="flm-form-container">
        <div class="flm-form-section">
          <h3 class="flm-section-title">基本信息</h3>
          <el-row :gutter="24" class="flm-row">
            <el-col :xs="24" :sm="12" :md="8" :lg="8">
              <div class="flm-form-item">
                <label class="flm-item-label">任务ID</label>
                <el-input v-model="formData.taskId" placeholder="请输入任务ID" class="flm-input"></el-input>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8">
              <div class="flm-form-item">
                <label class="flm-item-label">数据集</label>
                <el-select v-model="formData.splitMethod" placeholder="请选择数据集" class="flm-input">
                  <el-option v-for="option in splitMethodOptions" :key="option.value" :label="option.label"
                    :value="option.value"></el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8">
              <div class="flm-form-item">
                <label class="flm-item-label">批量大小</label>
                <el-input v-model.number="formData.batchSize" type="number" placeholder="请输入批量大小"
                  class="flm-input"></el-input>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="flm-row flm-mt-16">
            <el-col :xs="24" :sm="12" :md="8" :lg="8">
              <div class="flm-form-item">
                <label class="flm-item-label">聚合轮次</label>
                <el-input v-model.number="formData.aggregationRounds" type="number" placeholder="请输入聚合轮次"
                  class="flm-input"></el-input>
              </div>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="8">
              <div class="flm-form-item">
                <label class="flm-item-label">学习率</label>
                <el-input v-model.number="formData.learningRate" type="number" step="0.001" placeholder="请输入学习率"
                  class="flm-input" @input="handleInput"></el-input>
              </div>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="8">
              <div class="flm-form-item">
                <label class="flm-item-label">训练轮数</label>
                <el-input v-model.number="formData.epochs" type="number" placeholder="请输入训练轮数"
                  class="flm-input"></el-input>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="flm-action-group flm-mt-48"
          style="display: flex; justify-content: flex-start; padding: 0; margin:20px 10px 0 0;">
          <el-button type="primary" @click="handleSubmit" style="margin-top: 20px;">
            创建任务
          </el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog :visible.sync="detailDialogVisible" title="任务详情" width="600px" :close-on-click-modal="false">
  <div v-loading="detailLoading">
    <!-- 任务ID -->
    <div class="detail-item">
      <span class="detail-label">任务ID：</span>
      <span class="detail-value">{{ currentTaskId || '-' }}</span>
    </div>
    <!-- 客户端列表 -->
    <el-divider content-position="left">客户端状态</el-divider>
    <div class="client-list">
      <div v-for="clientId in clientIds" :key="clientId" class="client-item">
        <div class="client-id">{{ clientId }}</div>
        <div class="client-action">
          <template v-if="currentTaskStatus === '执行中'">
            <!-- 加入处理null的兜底逻辑 -->
            <el-button v-if="!((clientIds1 || []).includes(clientId))" type="primary" size="mini"
              @click="joinTask(clientId, currentTaskId)">加入训练</el-button>

            <el-tag v-else type="success" size="mini">已加入 (任务: {{ currentTaskId }})</el-tag>
          </template>

          <el-tag v-else type="info" size="mini">
            {{ currentTaskStatus === '待执行' ? '任务未开始' : '任务已结束' }}
          </el-tag>
        </div>
      </div>
    </div>
    <!-- 新增 ECharts 图表容器 -->
    <div v-if="currentTaskStatus === '已完成'" id="echarts-container" style="width: 100%; height: 300px;"></div>
  </div>

  <template #footer>
    <el-button @click="detailDialogVisible = false">关 闭</el-button>
  </template>
</el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'; // 引入 ECharts
import axios from 'axios';
import { getTrainingRoundById } from '@/api/flTrainingRound'; // 导入接口
import { getRecord, getBlockAndContractInfo } from '../../web3/fl';
import { addClient, deleteClient, updateClient, getTaskId, getAllClients, getClientsByPage, updateClientTasks } from '@/api/flClient'; // 导入接口
import { getTrainingTasksByPage, addTrainingTask, deleteTrainingTask, updateTrainingTask, getTrainingTaskById, getAllTrainingTasks } from '@/api/flTrainingTask'; // 导入接口
export default {
  data() {
    return {
      searchValue: null,
      tableData: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      port: 6002,
      drawerVisible: false,
      formData: {
        taskId: '',
        splitMethod: '',
        batchSize: null,
        aggregationRounds: null,
        learningRate: '',
        epochs: null,
        status: ''

      },
      splitMethodOptions: [
        { label: 'ByClass', value: 'byclass' },
        { label: 'ByMerge', value: 'bymerge' },
        { label: 'Balanced', value: 'balanced' },
        { label: 'Letters', value: 'letters' },
        { label: 'Digits', value: 'digits' },
        { label: 'MNIST', value: 'mnist' }
      ],
      detailDialogVisible: false,
      currentTaskId: null,
      currentTaskStatus: null,
      detailLoading: false,
      clientIds: ['client1', 'client2'],
      clientIds1: [],
      clientInfos: {} // 从数组改为对象，以clientId为键
    };
  },
  mounted() {
    this.loadTaskList();
    // this.fetchRecord();
    // this.fetchBlockInfo();
  },
  methods: {
    async fetchRecord() {
      const result = await getRecord('task_210');
      if (result.success) {
        console.log('Record data:', result.data);
      } else {
        console.error('Error:', result.error);
      }
    },
    // 获取区块信息
    async fetchBlockInfo() {
      try {
        const result = await getBlockAndContractInfo(3)
        if (result.success) {
          console.log('区块信息:', result)
        } else {
          console.error('获取失败:', result.error || '未知错误')
        }
      } catch (e) {
        console.error('捕获异常:', e.message)
      }
    },
    async loadTaskList() {
      this.loading = true;
      try {
        const response = await getTrainingTasksByPage(
          { taskId: this.searchValue }, // 筛选条件（可扩展）
          this.pageNum,
          this.pageSize
        );
        this.tableData = response.data.list; // 表格数据
        this.total = response.data.total; // 总记录数
      } catch (error) {
        console.error('加载任务失败:', error);
        this.$message.error('任务加载失败，请重试');
      } finally {
        this.loading = false;
      }
    },
    handlePageSizeChange(size) {
      this.pageSize = size;
      this.pageNum = 1; // 切换页大小后重置为第一页
      this.loadTaskList();
    },
    handleCurrentPageChange(page) {
      this.pageNum = page;
      this.loadTaskList();
    },
    async handleEdit(row) {
      try {
        const response = await axios.post('http://localhost:5000/fl/start_server', {
          "task_id": row.taskId,
          "port": this.port + Math.floor(Math.random() * 1000),
          "total_runs": row.aggregationRounds,
          "split": row.splitMethod,
          "learning_rate": row.learningRate,
          "epochs": row.epochs,
          "aggregation_rounds": row.aggregationRounds
        });
        if (response.data.code === 200) {
          getTrainingTaskById(row.taskId).then(response => {
            console.log('response', response);
            // 检查 response.data 是否包含任务数据
            if (response.data && response.data.data) {
              const data = response.data.data;
              data.status = '执行中';
              updateTrainingTask(data).then(response => {
                this.$message.success('任务状态更新成功');
                this.loadTaskList();
              }).catch(error => {
                console.error('任务状态更新失败', error);
                this.$message.error('任务状态更新失败，请重试');
              });
            } else if (response.data) {
              // 假设实际数据就在 response.data 中
              const data = response.data;
              data.status = '执行中';
              updateTrainingTask(data).then(response => {
                this.$message.success('任务状态更新成功');
                this.loadTaskList();
              }).catch(error => {
                console.error('任务状态更新失败', error);
                this.$message.error('任务状态更新失败，请重试');
              });
            } else {
              console.error('获取任务数据失败，数据格式错误');
              this.$message.error('获取任务数据失败，请重试');
            }
          }).catch(error => {
            console.error('获取任务数据失败', error);
            this.$message.error('获取任务数据失败，请重试');
          });
          this.$message.success(response.data.message);
        } else {
          this.$message.error(response.data.error);
        }
      } catch (error) {
        console.error('服务启动失败', error);
        this.$message.error('服务启动失败，请重试');
      }
    },
    // 删除任务（优化参数传递）
    handleDelete(taskId) {
      // 调用删除API
      // deleteTrainingTask(taskId).then(...).catch(...)
      console.log('删除任务ID:', taskId);
    },
    formatDateTime(isoTime) {
      if (!isoTime) return '-';
      const date = new Date(isoTime);
      return date.toLocaleString().replace(/:/g, '-'); // 转换为本地时间格式
    },

    handleDistributionChange(value) {
      console.log('Selected distribution:', value)
      // 这里可以添加选择后的处理逻辑
    },
    handleSubmit() {
      const learningRate = parseFloat(this.formData.learningRate);
      if (isNaN(learningRate)) {
        console.error('输入的学习率不是有效的数字');
        return;
      }
      this.formData.learningRate = learningRate;
      // 调用添加训练任务的接口
      const currentDate = new Date().toISOString();
      const data = {
        ...this.formData,
        createdAt: currentDate,
        status: '待执行'
      };
      addTrainingTask(data)
        .then(response => {
          console.log('任务添加成功', response.data);
          this.drawerVisible = false;
          this.loadTaskList();
        })
        .catch(error => {
          console.error('任务添加失败', error);
        });
    },
    openDrawer() {
      this.drawerVisible = true;
      this.formData = {
        taskId: '',
        splitMethod: '',
        batchSize: null,
        aggregationRounds: null,
        learningRate: null,
        epochs: null,
        status: ''
      };
    },
    handleInput(value) {
      this.formData.learningRate = value;
    },
    handleSearch() {
      if (this.searchValue) {
        this.pageNum = 1; // 重置页码为第一页
        this.loadTaskList();
      } else {
        this.$message.warning('请输入查询条件');
      }
    },
    handleClearSearch() {
      this.searchValue = null;
      this.pageNum = 1;
      this.loadTaskList();
    },
    getButtonType(status) {
      switch (status) {
        case '待执行':
          return 'primary';
        case '执行中':
          return 'info';
        case '已完成':
          return 'success';
        default:
          return 'primary';
      }
    },
    getButtonText(status) {
      switch (status) {
        case '待执行':
          return '启动服务';
        case '执行中':
          return '执行中';
        case '已完成':
          return '已完成';
        default:
          return '启动服务';
      }
    },
    async handleDetail(row) {
      try {
        this.detailLoading = true;
        this.detailDialogVisible = true;
        this.currentTaskId = row.taskId;
        this.currentTaskStatus = row.status;
        const responses = await getTaskId(this.currentTaskId);
        this.clientIds1 = Array.isArray(responses?.data) ? responses.data : [];
        const res = await getTrainingRoundById(this.currentTaskId);
        const roundNumbers = res.data.map(item => item.roundNumber);
        const trainAccs = res.data.map(item => item.trainAcc);
        const testAccs = res.data.map(item => item.testAcc);
        // ECharts 配置项
        const option = {
          title: {
            text: '训练和测试准确率随轮次变化'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: roundNumbers
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '训练准确率',
              data: trainAccs,
              type: 'line'
            },
            {
              name: '测试准确率',
              data: testAccs,
              type: 'line'
            }
          ]
        };
        if (this.currentTaskStatus === '已完成') {
          const chartDom = document.getElementById('echarts-container');
          const myChart = echarts.init(chartDom);
          myChart.setOption(option);
        }
      } catch (error) {
        console.error('加载详情失败:', error);
        this.$message.error('客户端状态加载失败');
        // 错误时也保持数组类型
        this.clientIds1 = [];
      } finally {
        this.detailLoading = false;
      }
    },
    async joinTask(clientId, taskId) {
      try {
        const response = await addClient({ clientId, taskId });
        if (response.code === '200') {
          const response = await axios.post('http://localhost:5000/fl/start_client', {
            "client_id": clientId
          });
          const responses = await getTaskId(this.currentTaskId);
          // 处理null/undefined的兜底逻辑
          this.clientIds1 = Array.isArray(responses?.data) ? responses.data : [];
          this.$message.success(`客户端 ${clientId} 成功加入任务`);
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        this.clientIds1 = [];
        console.error('加入任务失败', error);
      }
    }
  }
};
</script>
<style scoped>
/* 新增样式 */
.flm-form-container {
  background: #ffffff;
  padding: 5px;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
}

.flm-form-section {
  padding: 18px;
  border: 1px solid #dad9d98e;
  border-radius: 8px;
  background: #ffffff;
  margin-top: 5px;
}

.flm-form-item {
  display: flex;
  align-items: center;
  min-height: 40px;
}

.el-input-number.flm-input {
  width: 100%;
}

/* 选择框下拉面板样式 */
.el-select-dropdown {
  max-width: 300px;
}

/* 空列隐藏边框 */
.el-col:empty {
  border: 0;
}

.flm-item-label {
  display: inline-block;
  width: 120px;
  /* 统一标签宽度 */
  margin-right: 16px;
  text-align: right;
  color: #606266;
  font-size: 14px;
  vertical-align: middle;
}

.flm-input {
  flex: 1;
  max-width: 300px;
}

/* 新增样式 */
.flm-placeholder {
  visibility: hidden;
  /* 隐藏占位元素但保留布局空间 */
}

.el-input-number.flm-input>>>.el-input__inner {
  padding-right: 15px;
  /* 优化数字输入框右侧间距 */
}

/* 参数范围提示 */
.flm-form-item:hover .el-input__suffix {
  visibility: visible;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .flm-form-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .flm-item-label {
    width: 100%;
    text-align: left;
    margin-bottom: 8px;
  }

  .flm-input {
    max-width: 100%;
  }
}

/* 行间距调整 */
.flm-row {
  margin-bottom: -5px;
}

.flm-mt-16 {
  margin-top: 16px;
}

/* 样式增强 */
.detail-item {
  margin: 12px 0;
  font-size: 14px;
}

.detail-label {
  display: inline-block;
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.client-list {
  margin-top: 16px;
}

.client-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  margin: 8px 0;
  border-radius: 4px;
  background: #f5f7fa;
}

.client-id {
  font-family: monospace;
  color: #409eff;
}

.client-action {
  min-width: 120px;
  text-align: right;
}

/* 加载动画优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}
</style>
